package com.daily.daily_push;

import io.kubernetes.client.custom.IntOrString;
import io.kubernetes.client.custom.Quantity;
import io.kubernetes.client.openapi.models.*;
import io.kubernetes.client.util.Yaml;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class testYaml {
    public static void main(String[] args) throws IOException {
            // 创建Deployment对象
            Map<String, String> matchLabels = new HashMap<>();
            matchLabels.put("app", "apptest");
            Map<String, String> templateLabels = new HashMap<>();
            templateLabels.put("app", "apptest");
            //labels
            Map<String, String> labels = new HashMap<>();
            labels.put("app","apptest");
            //resource资源
            Map<String, Quantity> requests = new HashMap<>();
            requests.put("memory", new Quantity("1024Mi"));
            requests.put("cpu", new Quantity("1"));
            Map<String, Quantity> limits = new HashMap<>();
            limits.put("memory", new Quantity("1024Mi"));
            limits.put("cpu", new Quantity("1"));


            V1Deployment deployment = new V1Deployment()
                    .apiVersion("apps/v1")
                    .kind("Deployment")
                    .metadata(new V1ObjectMeta().name("my-deployment").namespace("default").labels(labels))
                    .spec(new V1DeploymentSpec()
                            .replicas(3)
                            .selector(new V1LabelSelector().matchLabels(matchLabels))
                            .template(new V1PodTemplateSpec()
                                    .metadata(new V1ObjectMeta().labels(templateLabels))
                                    .spec(new V1PodSpec()
                                            .containers(Arrays.asList(new V1Container()
                                                    .name("apptest")
                                                    .image("111.230.74.250/library/app1@sha256:81182cae3bb34f3658ba34bbfc8305d26b225ef431139ee96271a475fbcf77d0")
                                                    .imagePullPolicy("IfNotPresent")
                                                    .resources(new V1ResourceRequirements()
                                                            .requests(requests)
                                                            .limits(limits))))
                                            .imagePullSecrets(Arrays.asList(new V1LocalObjectReference().name("docker-login")))
                                            .dnsPolicy("ClusterFirst")
                                            .restartPolicy("Always")
                                    )));







            // 创建Service对象
            Map<String, String> selector = new HashMap<>();
            selector.put("app", "apptest");

            V1Service service = new V1Service()
                    .apiVersion("v1")
                    .kind("Service")
                    .metadata(new V1ObjectMeta().name("apptest").namespace("default"))
                    .spec(new V1ServiceSpec()
                            .type("NodePort")
                            .ports(Arrays.asList(new V1ServicePort()
                                    .name("apptestport")
                                    .port(8081)
                                    .targetPort(new IntOrString(8088))
                                    .nodePort(30000)))
                            .selector(selector));

            // 将Deployment和Service对象序列化为YAML字符串
            StringWriter writer = new StringWriter();
            Yaml.dump(deployment, writer);
            writer.write("---\n");
            Yaml.dump(service, writer);
            String yaml = writer.toString();

            // 输出YAML字符串
            System.out.println(yaml);

            String filePath = "D:\\commonTest\\k8s\\autoYaml\\test1\\apptest.yaml";
            File file = new File(filePath);
            if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
            }

            try (FileWriter fileWriter = new FileWriter(file)) {
                    fileWriter.write(yaml);
            } catch (IOException e) {
                    e.printStackTrace();
            }


         /*   // 将YAML字符串写入文件   windos
            try (FileWriter fileWriter = new FileWriter("D:\\commonTest\\k8s\\autoYaml\\apptest.yaml")) {
                fileWriter.write(yaml);
            } catch (IOException e) {
                e.printStackTrace();
            }*/


/*
// 将YAML字符串写入文件   linux
        // 自定义输出文件路径
        String outputDirectory = "/home/myaml/v1/20230711";
        String outputFilePath = outputDirectory + "/my.yaml";

        // 创建目录
        File directory = new File(outputDirectory);
        if (!directory.exists()) {
            if (directory.mkdirs()) {
                System.out.println("目录创建成功：" + outputDirectory);
            } else {
                System.out.println("无法创建目录：" + outputDirectory);
                return;
            }
        }
        // 将YAML字符串写入文件
        try (FileWriter fileWriter = new FileWriter(outputFilePath)) {
            fileWriter.write(yaml);
            System.out.println("文件写入成功：" + outputFilePath);
        } catch (IOException e) {
            e.printStackTrace();
        }*/


//        替换ansible-playboot 配置文件进行

/*        String playbookFile = "/home/playbook.yml"; // playbook文件路径

        // 从数据库获取变量值（此处仅为示例，您需要根据实际情况修改）
        String yamlHome = "/path/to/yaml/home";
        String yaml1 = "my-yaml-file.yaml";

        // 读取playbook文件内容
        String content = new String(Files.readAllBytes(Paths.get(playbookFile)), StandardCharsets.UTF_8);

        // 替换变量
        content = content.replace("{{ yaml_home }}", yamlHome);
        content = content.replace("{{ yaml }}", yaml);

        // 将更新后的内容写回文件
        Files.write(Paths.get(playbookFile), content.getBytes(StandardCharsets.UTF_8));
    }
        */


    }

}
